<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/8
 * Time: 17:05
 */



// 协程 开发案例
class Coroutines
{
    public function index()
    {
//        开启协程
        go(function () {
            $time = time();
            $swoole_mysql = new Swoole\Coroutine\MySQL();
            $swoole_mysql->connect([
                'host' => '127.0.0.1',
                'port' => 3306,
                'user' => 'root',
                'password' => 'liuqiang',
                'database' => 'test',
            ]);
            $swoole_mysql->setDefer();//延迟收包
            $swoole_mysql->query('select sleep(3)');

            $swoole_mysql1 = new Swoole\Coroutine\MySQL();
            $swoole_mysql1->connect([
                'host' => '127.0.0.1',
                'port' => 3306,
                'user' => 'root',
                'password' => 'liuqiang',
                'database' => 'test',
            ]);
            $swoole_mysql1->setDefer();//延迟收包
            $swoole_mysql1->query('select sleep(2)');
            var_dump($swoole_mysql->recv(), $swoole_mysql1->recv());
            echo time() - $time;
        });

        echo '异步网络请求';


//        创建http请求
        $num = 10;
        $reslut = [];
        for ($i = 0; $i <= $num; $i++) {
//            创建http请求
            $cli = new Swoole\Coroutine\Http\Client('127.0.0.1', 1314);
            $cli->set(['timeout' => 4]);//设置请求时间
            $cli->setDefer();//延迟收包
            $data = [
                'userName' => 'liuqiang' . $i,
                'sel' => 5
            ];
            $cli->post('/', $data);
//            echo $cli->body;
//            $cli->close();
            $reslut[$i] = $cli;
        }

        foreach ($reslut as $v) {
            $res = $v->recv();//接收包
            var_dump($res);
        }

    }

    /**
     *  测试案例利用协程与以太坊交互
     */
    public function test()
    {
        //开启协程
        go(function () {
            $time = time();
            //        创建http请求
            $reslut = [];
            $address = [
                '0x7b5598c659FfDa9ccC0DD05dac5678deDf088B7a',
                '0xa838be6E4b760E6061D4732D6B9F11Bf578f9A76',
                '0x7EC4d225481F8bada87552e59C0a9DBFc5B10b2f'
            ];
            foreach ($address as $v) {
                //            创建http请求
                $cli = new Swoole\Coroutine\Http\Client('node3.web3api.com', 80);
                $cli->set(['timeout' => 5]);//设置请求时间
                $cli->setHeaders(['Content-Type' => "application/json",]);
                $cli->setDefer();//延迟收包
                $data = array(
                    'jsonrpc' => '2.0',
                    'method' => 'eth_getBalance',
                    'params' => array($v, 'latest'),
                    'id' => 1
                );
                $cli->post('/', json_encode($data));
                $reslut[$v] = $cli;
//              var_dump($cli->body);
            }
            foreach ($address as $v) {
                $reslut[$v]->recv();//接收包
                // 获取返回文本内容
                $res = json_decode($reslut[$v]->body);
                $priceEth = hexdec(str_replace("0x", "", $res["result"]));
                var_dump(json_encode([$v => $priceEth / pow(10, 18)]));
            }
            echo $time - time();
        });

    }

    /**
     * 创建一个http协议服务
     */
    public function server()
    {
        // 创建http协议服务
        $http = new Swoole\Http\Server("0.0.0.0", 1314);
//        绑定http事件
//        $request，获取Http请求信息对象，包含了header/get/post/cookie等相关信息
//$response，Http响应对象，支持cookie/header/status等Http操作
        $http->on('request', function ($request, $response) {
            $req = $request->post;
            //sleep($req['sleep']);
            Swoole\Coroutine::sleep($req['sleep']);//swoole级别睡眠
            //响应事件
            $response->end($req['userName']);
        });
        // 开启服务
        $http->start();
    }


}